﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.ComponentModel;
using System.Collections;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging; 
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Runtime.InteropServices;
  
namespace TakeNote
{
    public partial class Window1 : Window
    {          
        TransformGroup transformGroup;
        ScaleTransform scaleTransform;
        TranslateTransform translateTransform;    
        
        private double DefaultZoomFactor=0;
        //InkCanvas 

        public Window1()
        {
            InitializeComponent();
            //포커스 상관없이 전역으로 키 캡쳐

            //듀얼 모니터나 가상 모니터 사용시의 방법
            //System.Windows.Forms.SystemInformation.VirtualScreen.Width;
            //System.Windows.Forms.SystemInformation.VirtualScreen.Height;
            
            //this.Topmost = true;
            //double height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
            //double width1 = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;  //전체 가로 크기
            //double width = height * 4 / 3; // 비율상 widh크기 구하기         
            //this.Left = (width1 - width) / 2;
            //this.Width = width;
            //this.Height = height;
            //this.Top = 0;
            
            EventManager.RegisterClassHandler(typeof(Window), Keyboard.KeyDownEvent,
                                    new KeyEventHandler(Window_KeyDown), true);
            //////////////////////////////////////////////////////////
            transformGroup = new TransformGroup();
            scaleTransform = new ScaleTransform();
            
            translateTransform = new TranslateTransform();
            
            transformGroup.Children.Add(scaleTransform);
            transformGroup.Children.Add(translateTransform);

            inkCanvas.RenderTransform = transformGroup;
            inkCanvas.MouseWheel += ImageViewboxMouseWheel;
                        

            DrawBoldLine(100, 200, 400, 400);
            DrawBoldLine(400, 400, 600, 600);
        }
 
        private void DrawBoldLine(int x1, int y1, int x2, int y2)//굵은선 그리기
        {
            Color color = Color.FromRgb(148, 170, 59);//(r,g,b)값
            SolidColorBrush brush = new SolidColorBrush(color);//브러쉬 색설정
            Line line = new Line();//라인 생성
            
            line.X1 = x1;//좌표설정
            line.X2 = x2;//좌표설정
            line.Y1 = y1;//좌표설정
            line.Y2 = y2;//좌표설정
            line.Stroke = brush;//선색 지정
            line.Fill = brush;//면색 지정
            line.StrokeThickness = 2;//선두께 정
            inkCanvas.Children.Add(line);//캔버스에 집어넣기
        }

        void ImageViewboxMouseWheel(object sender, MouseWheelEventArgs e)
        {
            inkCanvas.RenderTransformOrigin = new Point(0, 0);
            double zoomFactor = DefaultZoomFactor;
            if (e.Delta <= 0) zoomFactor = 1.0;// DefaultZoomFactor;
            // DoZoom requires both the logical and physical location of the mouse pointer
            var physicalPoint = e.GetPosition(inkCanvas);
            if (transformGroup.Inverse != null)
            {
                DoZoom(zoomFactor, transformGroup.Inverse.Transform(physicalPoint), physicalPoint);
            }
            else
            {
                throw new ArgumentException("Missing Inverse");
            }

            //Set the center point of the ScaleTransform object to the cursor location.
            scaleTransform.CenterX = e.GetPosition(inkCanvas).X;
            scaleTransform.CenterY = e.GetPosition(inkCanvas).Y;
           // Debug.WriteLine(string.Format("IVMW Center {0},{1}", scaleTransform.CenterX, scaleTransform.CenterY));
        }

        public void DoZoom(double deltaZoom, Point mousePosition, Point physicalPosition)
        {
            double currentZoom = scaleTransform.ScaleX;
            currentZoom *= deltaZoom;

            translateTransform.X = -1 * (mousePosition.X * currentZoom - physicalPosition.X);
            translateTransform.Y = -1 * (mousePosition.X * currentZoom - physicalPosition.Y);
            scaleTransform.ScaleX = currentZoom;
            scaleTransform.ScaleY = currentZoom;

        }
        
        private void ChangePenColor(Color color)
        {
            this.inkCanvas.DefaultDrawingAttributes.Color = color;
        }

        private void 형광(Color color)
        {
            this.inkCanvas.DefaultDrawingAttributes.Color = color;
            this.inkCanvas.DefaultDrawingAttributes.Width = 15;
            this.inkCanvas.DefaultDrawingAttributes.Height = 15;
        }
        
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Escape:
                    this.Close();
                    break;

                case Key.F1://빨강
                    ChangePenColor(Color.FromRgb(255, 0, 0));
                     break;

                case Key.F2:                    //파랑
                    ChangePenColor(Color.FromRgb(0, 0, 255));
                    break;

                case Key.F3:                    
                    //  형광(Colors.GreenYellow);
                    형광(Color.FromArgb(100, 255, 228, 0));
                    break;

                case Key.F4:
                    //지우기
                    inkCanvas.EditingMode = InkCanvasEditingMode.EraseByStroke;
                    break;

                case Key.F5:
                    // 마우스 움직임으로지우기
                    inkCanvas.EraserShape = new EllipseStylusShape(70, 70);
                    inkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                    break;

                case Key.PrintScreen:
                    //이미지 캡쳐
                    RenderTargetBitmap bitmap = ConverterBitmapImage(inkCanvas);
                    ImageSave(bitmap);
                    break;

                case Key.A:
                    // 슬라이드 이동
                    //  ppt.SlideShowWindow.View.GotoSlide(4, MsoTriState.msoTrue);
                    //SlideShowWindow.View.Next SlideShowWindow.View.Previous .                
                    //ppt.SlideShowWindow.View.Next();
                    break;
            }
        }

        private void inkCanvas_PreviewMouseRightButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            inkCanvas.Strokes.Clear();

        }
  
        // 해당 객체를 이미지로 변환
        private static RenderTargetBitmap ConverterBitmapImage(FrameworkElement element)
        {
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();

            // 해당 객체의 그래픽요 소로 사각형의 그림을 그립니다.
            drawingContext.DrawRectangle(new VisualBrush(element), null,
                new Rect(new Point(0, 0), new Point(element.ActualWidth, element.ActualHeight)));
            drawingContext.Close();
            
            // 비트맵으로 변환합니다.
            RenderTargetBitmap target =
                new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight,
                96, 96, System.Windows.Media.PixelFormats.Pbgra32);

            target.Render(drawingVisual);
            return target;
        }

        // 해당 이미지 저장
        private static void ImageSave(BitmapSource source)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();

            // 이미지 포맷들
            saveDialog.Filter = "PNG|*.png|JPG|*.jpg|GIF|*.gif|BMP|*.bmp";
            saveDialog.AddExtension = true;

            if (saveDialog.ShowDialog() == true)
            {
                BitmapEncoder encoder = null;
                // 파일 생성
                FileStream stream = new FileStream(saveDialog.FileName, FileMode.Create, FileAccess.Write);

                // 파일 포맷
                string upper = saveDialog.SafeFileName.ToUpper();
                char[] format = upper.ToCharArray(saveDialog.SafeFileName.Length - 3, 3);
                upper = new string(format);

                // 해당 포맷에 맞게 인코더 생성
                switch (upper.ToString())
                {
                    case "PNG":
                        encoder = new PngBitmapEncoder();
                        break;
                    case "JPG":
                        encoder = new JpegBitmapEncoder();
                        break;
                    case "GIF":
                        encoder = new GifBitmapEncoder();
                        break;
                    case "BMP":
                        encoder = new BmpBitmapEncoder();
                        break;
                }
                // 인코더 프레임에 이미지 추가
                encoder.Frames.Add(BitmapFrame.Create(source));
                // 파일에 저장
                encoder.Save(stream);

                stream.Close();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

    }
}